<template>
    <div>
        <el-dialog
                :visible.sync="dialogVisible"
                :title.sync="title"
                center
                @open="init"
                lock-scroll
                width="1080px"
                :append-to-body="true">
            <div style="width: 100%;">
                <el-form>
                    <el-form-item label="选择标签">
                        <el-select v-model="search.LabelKey" placeholder="请选择标签" @change="selectedLabel()">
                            <el-option v-for="(label, idx) in labels" :key="idx" :value="label.Key" :label="label.Name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-upload
                                ref="upload"
                                class="upload-demo"
                                name="Image"
                                action="/admin/images"
                                multiple
                                :http-request="uploadImage"
                                :before-upload="beforeUpload"
                                :data.sync="search"
                                :on-success="handleUploadSuccess"
                                list-type="picture">
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div v-if="images.length>0">
                    <div>
                        <el-checkbox :indeterminate="checkBox.isIndeterminate" v-model="checkBox.checkAll" @change="handleCheckAllImage">全选</el-checkbox>
                        <el-button
                                v-if="checkBox.checkedImages.length>0"
                                size="mini"
                                type="warning"
                                @click="handleDelete()">删除</el-button>
                    </div>
                    <div style="margin: 15px 0;"></div>
                    <div class="images-container">
                        <el-checkbox-group v-model="checkBox.checkedImages" @change="handleCheckedImages">
                            <el-checkbox v-for="img in images" :key="img.ID + ''" :label="img.ID + ''">
                                <div class="image-container">
                                    <img @click.stop.prevent="selectImage(img)" :src="$axios.defaults.imgURL + img.File" class="avatar" style="width: 100%;height: auto;display: block;" :alt="img.File">
                                </div>
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div class="pagination">
                        <el-pagination
                                style="margin: 10px 0"
                                background
                                @current-change="selectImages"
                                :current-page.sync="page.current"
                                @size-change="handleSizeChange"
                                :page-sizes="[5, 10, 20]"
                                :page-size="search.Limit"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="page.total">
                        </el-pagination>
                    </div>
                </div>
                <div v-else>
                    <h3>暂无数据</h3>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
        props:{
            "visible":Boolean,
            "title":String,
            "handleSelect": Function,
            "uniqueLabel": String,
        },
        computed: {
            dialogVisible: {
                get: function () {
                    return this.visible
                },
                set: function (v) {
                    this.$emit("update:visible", v)
                }
            },
        },
    data() {
        return {
            "labels": [
                {
                    "ID": 0,
                    "Name": "",
                    "Key": "",
                    "Width": 0,
                    "Height": 0,
                    "AllowedEdit": 0,
                    "SizeKB": 0
                }
            ],
            search:{
                LabelKey:"",
                Limit: 10,
                Offset: 0,
            },
            page: {
                total: 0,
                current: 0,
            },
            "images": [
                // {
                //     "ID": 0,
                //     "AdminID": 0,
                //     "File": "",
                //     "Label": 0,
                //     "LabelKey": "",
                //     "CreatedAt": null
                // }
            ],
            checkBox: {
                checkAll: false,
                isIndeterminate: false,
                checkedImages:[],
            },
            inited: false
        }
    },
    methods: {
        selectImage(img){
            this.handleSelect(img.File);
            this.dialogVisible=false;
        },
        init(){
            if(!this.inited) {
                this.$axios.get("/admin/image-labels").then((resp)=>{
                    if(resp.data.labels) {
                        this.labels = resp.data.labels;
                        this.inited = true;
                        this.initLocalLabel();
                    }
                });
            }
        },
        initLocalLabel(){
            if(this.uniqueLabel) {
                this.search.LabelKey = localStorage.getItem("imageLabelKey-" + this.uniqueLabel);
                if(this.search.LabelKey) {
                    this.countImages();
                }
            }
        },
        setLocalLabel(){
            if(this.uniqueLabel) {
                localStorage.setItem("imageLabelKey-" + this.uniqueLabel, this.search.LabelKey);
            }
        },
        selectedLabel(){
            this.setLocalLabel();
            this.countImages()
        },
        handleSizeChange(val) {
            this.search.Limit = val;
            this.selectImages(1)
        },
        selectImages(page) {
            this.search.Offset = (page - 1) * this.search.Limit;
            this.$axios.get("/admin/label-images", {params: this.search}).then((resp)=>{
                if(resp.data.images) {
                    this.images = resp.data.images
                } else {
                    this.images = [];
                }
            });
        },
        countImages() {
            this.images = [];
            this.$axios.get("/admin/count-images", {params: {LabelKey: this.search.LabelKey}}).then((resp)=>{
                if(resp.data.total) {
                    this.page.total = resp.data.total;
                    this.page.current = 0;
                    this.selectImages(1);
                }
            });
        },
        handleCheckedImages(value) {
            let checkedCount = value.length;
            this.checkBox.checkAll = checkedCount === this.images.length;
            this.checkBox.isIndeterminate = checkedCount > 0 && checkedCount < this.images.length;
        },
        handleCheckAllImage(val) {
            this.checkBox.checkedImages = [];
            if(val) {
                for(let img of this.images) {
                    this.checkBox.checkedImages.push(img.ID + "")
                }
            }
            this.checkBox.isIndeterminate = false;
        },
        uploadImage(item) {
            this.$uploadElementItem(item).then(res => {
                if(res.data.images) {
                    for(let image of res.data.images) {
                        this.images.unshift(image)
                    }
                }
            })
        },
        beforeUpload() {
            return this.isAllowedEdit()
        },
        isAllowedEdit(){
            for(let label of this.labels) {
                if(label.Key === this.search.LabelKey) {
                    if(label.AllowedEdit!==1) {
                        this.$alert("当前标签下的图片被禁止操作");
                        return false
                    } else {
                        return true
                    }
                }
            }
            this.$alert("未选择标签");
            return false
        },
        handleUploadSuccess(res,) {
            if(res.images) {
                for (let i = 0, ln=res.images.length; i < ln; i++) {
                    let img = res.images[i];
                    this.images.splice(0,0,img);
                }
                this.$refs.upload.clearFiles()
            }
        },
        handleDelete() {
            if (this.isAllowedEdit()) {
                let ids = this.checkBox.checkedImages;
                this.$confirm("确认删除所有选中图片?").then(() => {
                    this.$axios.delete("/admin/label-images", {params: {IDs: ids}}).then((resp)=>{
                        if(this.$isSuccessMsg(resp)) {
                            for (let j = 0, ln = ids.length; j < ln; j++) {
                                for (let i = 0; i < this.images.length; i++) {
                                    let img = this.images[i];
                                    if (img.ID === ids[j]) {
                                        this.images.splice(i, 1)
                                    }
                                }
                            }
                            this.checkBox.checkedImages = [];
                            this.checkBox.isIndeterminate = false;
                            this.selectImages(this.page.current)
                        }
                    })
                })
            }
        },
    }
}
</script>
<style>
    .images-container .el-checkbox {
        position: relative;
        margin: 20px;
    }
    .images-container .el-checkbox .el-checkbox__input {
        position: absolute;
        top: 10px;
        left: 10px;
    }
    .images-container .el-checkbox .el-checkbox__label {
        padding: 0;
    }
    .image-container {
        width: 160px;
        overflow: hidden;
    }
</style>
